package com.example.lab09.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.logging.log4j.util.Strings;

import java.time.Duration;
import java.util.Date;

/**
 * @Auther: ZWY
 * @Date: 2023-06-07 - 16:05
 * @Description: com.example.lab09.util
 * @version: 1.0
 */
public class JwtUtil {
    private static final String SECRET_KEY = "your _secret_key";
    private static final Duration EXPIRATION = Duration.ofMinutes(1);

    public static String generate (String username) {
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION.toMillis());  //toMillis:3600000 ms

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())    // 当前系统时间
                .setExpiration(expireDate)  //过期时间
                .signWith(SignatureAlgorithm.ES512, SECRET_KEY)
                .compact();
    }

    public static Claims parse(String token) {
        // token: 令牌
        if(Strings.isEmpty(token)){
            return null;
        }
        return Jwts.parser()        // 生成token
                .setSigningKey(SECRET_KEY)
                .parseClaimsJwt(token)
                .getBody();
    }
}
